/*
 * Copyright (C) 2008  Young,Fey <fey.young@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */ 
package com.youngfey.wordmaster.database.tables

import com.youngfey.database.annotation.*
import com.youngfey.wordmaster.database.*
import static com.youngfey.wordmaster.database.Database.*

@HasMany(['CategoryIndex'])
@Unique(['NAME, PARENT']) //what if parent is null?
public class Category {
    String name

    @Nullable
    Category parent

    // <editor-fold defaultstate="collapsed" desc=" Generated Code (by gRDB)">
    Integer id
    

    boolean equals(Object o) {
        id != null && o instanceof Category && id == o.getId()
    }

    static createTable() {
        execute("CREATE TABLE Category (Id INT NOT NULL GENERATED ALWAYS AS IDENTITY CONSTRAINT CATEGORY_PK PRIMARY KEY, Name VARCHAR(255) NOT NULL, Parent INT)")
        
        execute('CREATE UNIQUE INDEX UIX_NAME_PARENT__CATEGORY ON Category (NAME, PARENT)')
        
    }

    boolean isValid() {
        name?.size() <= 255
    }


    boolean isConflicted() {
    
        def idUIX_NAME_PARENT = findIdByUIX_NAME_PARENT(nAME, pARENT)
        if(idUIX_NAME_PARENT != null && idUIX_NAME_PARENT != id) return true
    
        false
    }

    
    Integer findIdByUIX_NAME_PARENT(nAME, pARENT) {
        firstRow("SELECT ID FROM Category WHERE NAME = $nAME AND PARENT = $pARENT")?.id
    }
    


    static Category create(name, parent) {
        def instance = new Category(name: name, parent: parent)
        instance.insert()
        instance
    }

    def insert() {
        if(id == null && isValid()) {
            id = executeInsert("INSERT INTO Category (Name, Parent) VALUES (${name}, ${parent?.getId()})")[0][0]
            if(id != null) {
                
                return
            }
        }

        throw new IllegalStateException()
    }

    //capitalize;
    static Category find(Integer id) {
        if(id == null) return null

        

        def row = firstRow("SELECT * FROM Category WHERE Id = $id")
        
        row ? new Category(id: row.Id, name: row.name, parent: Category.find((Short)row.parent)) : null
        
    }

    static ArrayList<Category> findBySql(stmt) {
        def rows = []
        eachRow(stmt) {row ->
            rows << new Category(id: row.Id, name: row.name, parent: Category.find((Short)row.parent))
        }
        
        rows
    }

    static ArrayList<Category> findAll() {
        findBySql('SELECT * FROM Category')
    }

    
    static ArrayList<Category> findAll(String keyword) {
        findBySql("SELECT * FROM Category WHERE (Name LIKE $keyword)")
    }
    

    private executeUpdate(stmt) {
        def updated = executeUpdate(stmt)
        if(updated != 1) throw new IllegalStateException()
        
    }

    def update() {
        if(id != null && isValid()) {
            executeUpdate("UPDATE Category SET Name = ${name}, Parent = ${parent?.getId()} WHERE Id = $id")
        }
    }

    static delete(Integer id) {
        execute("DELETE FROM Category WHERE Id = $id")
        
    }

    def delete() {
        if(id != null) delete(id)
    }


    static ArrayList<Category> findByName(value) {
        findBySql("SELECT * FROM Category WHERE Name = ${value}")
    }

    static ArrayList<Category> findByParent(value) {
        findBySql("SELECT * FROM Category WHERE Parent = ${value?.getId()}")
    }



    static ArrayList<Category> findByNameLike(String keyword) {
        findBySql("SELECT * FROM Category WHERE Name LIKE $keyword")
    }

    static ArrayList<Category> findByParentLike(String keyword) {
        findBySql("SELECT * FROM Category WHERE Parent LIKE $keyword")
    }



    def updateName(value) {
        this.name = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE Category SET Name = ${value} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }

    def updateParent(value) {
        this.parent = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE Category SET Parent = ${value?.getId()} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }



    ArrayList<CategoryIndex> getCategoryIndexList() {
        CategoryIndex.findByCategory(this)
    }

    // </editor-fold>
}
